/*
 * Sensor.c
 *
 * Created: 2013-12-20 10:41:18
 *  Author: Fredrik
 */ 

#include "sensor.h"
#include "frequency_driver.h"
#include "adc_driver.h"
#include "string.h"
#include "avr_compiler.h"
#include "stdlib.h"
bool sampling = false;
int counter = 0; //Used for dummy values

void start_sampling();
void stop_sampling();
void init_sample_timer();
void read_digital_sensors();
void read_analog_sensors();

/* Used to start the continuous sampling if it is not already running*/
void start_sampling()
{
	if(!sampling){
		
		init_sample_timer();
		sampling = true;
		
	}
}

/*Stops the sampling timer*/
void stop_sampling()
{
	sampling = false;
	TCD0.CTRLA = 0; //Stop the timer
}


void read_digital_sensors(){
	int i;
	int data;
	for(i = 0; i < 4; i++){	
		set_active_sensor(i); //set the pin to read from
		start_frequency_measurement();	// take a frequency measurement	
		while(get_frequency_result() == -1); //wait for measurement to finish
		sensor_data[i] = get_frequency_result();//save the result
		clear_frequency_result();
	}
}

void read_analog_sensors(void)
{
	int i;
	for(i = 4; i < 8; i++){
		set_active_analog_sensor(i);
		sensor_data[i] = adc_read();
	}
}
void init_sample_timer(){
	

	/* Configure the timer for normal counting. */
	TCD0.CTRLB = TC_WGMODE_NORMAL_gc;
	
	/*The timer triggers an overflow interrupt when 1000 periods of the clock has passed.
	  This gives a overflow time of 0,512s with the timer clock set to 2Mhz/1024 = 1953Hz*/
	TCD0.PER = 1000; 

	/* Configure timer to generate a low level interrupt on overflow. */
	TCD0.INTCTRLA = TC_OVFINTLVL_LO_gc;
	
	/* This sets the counter clock to the system clock divided by 1024 and starts the timer */
	TCD0.CTRLA = TC_CLKSEL_DIV1024_gc;
}

/* Function to handle timer overflowing. */
ISR(TCD0_OVF_vect)
{
	if(sampling){
		counter++;
		read_digital_sensors();
		read_analog_sensors();
	}
}



